import 'dart:async';
import 'package:campus_vision/models/player/player_state.dart';
import 'package:campus_vision/providers/video_player_provider.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_vlc_player/flutter_vlc_player.dart';
import 'package:loading_animation_widget/loading_animation_widget.dart';

import '../../models/device/channel.dart';

class VideoPlayerWidget extends ConsumerWidget {
  final int deviceId;
  final Channel channel;
  VideoPlayerWidget({
    super.key,
    required this.deviceId,
    required this.channel,
  }) {
    debugPrint(
        "[player] 🆕 VideoPlayerWidget CONSTRUCTED ${deviceId}_${channel.id}");
  }

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    debugPrint("[player] VideoPlayerWidget b ${deviceId}_${channel.id}");
    return Container(
      color: Colors.black,
      child: Stack(
        fit: StackFit.expand,
        children: [
          _PlayerView(deviceId: deviceId, channelId: channel.id!),
          _TipsView(
              deviceId: deviceId, channelId: channel.id!), // ✅ 独立监听 playerState
          _ChannelName(channel.name ?? ''), // ✅ 静态组件，不监听状态

          // // 时间显示
          // Positioned(
          //   top: 4,
          //   right: 4,
          //   child: Container(
          //     padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 2),
          //     color: Colors.black54,
          //     child: const TimerWidget(),
          //   ),
          // ),
        ],
      ),
    );
  }
}

class _PlayerView extends ConsumerWidget {
  final int deviceId;
  final int channelId;
  const _PlayerView({
    required this.deviceId,
    required this.channelId,
  });
  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final hasController = ref.watch(
      videoPlayerStateProvider(deviceId, channelId)
          .select((state) => state.hasController),
    );
    if (!hasController) return const SizedBox.shrink();

    final controller =
        ref.read(videoPlayerStateProvider(deviceId, channelId)).controller!;
    debugPrint("[player] _PlayerView BUILD ${deviceId}_$channelId");

    return VlcPlayer(
      controller: controller,
      aspectRatio: 4.0 / 3.0,
    );
  }
}

class _TipsView extends ConsumerWidget {
  final int deviceId;
  final int channelId;

  const _TipsView({required this.deviceId, required this.channelId});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final playingState = ref.watch(
      videoPlayerStateProvider(deviceId, channelId)
          .select((state) => state.playerState),
    );

    if (playingState == PlayerState.playing ||
        playingState == PlayerState.paused) {
      return const SizedBox();
    }

    debugPrint("[player] _TipsView BUILD ${deviceId}_$channelId");
    return Center(
      child: LoadingAnimationWidget.staggeredDotsWave(
        color: Colors.white,
        size: 30,
      ),
    );
  }
}

class _ChannelName extends StatelessWidget {
  final String name;

  const _ChannelName(this.name);

  @override
  Widget build(BuildContext context) {
    return Positioned(
      top: 4,
      left: 4,
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 2),
        color: Colors.black54,
        child: Text(
          name,
          style: const TextStyle(color: Colors.white, fontSize: 10),
        ),
      ),
    );
  }
}

class TimerWidget extends StatefulWidget {
  const TimerWidget({super.key});

  @override
  State<StatefulWidget> createState() => _TimerWidgetState();
}

class _TimerWidgetState extends State<TimerWidget> {
  late Timer timer;
  String? _currentTime;
  @override
  void initState() {
    timer = Timer.periodic(const Duration(seconds: 1), _updateDisplayTime);
    super.initState();
  }

  @override
  void dispose() {
    timer.cancel();
    super.dispose();
  }

  void _updateDisplayTime(Timer timer) {
    final now = DateTime.now();
    setState(() {
      _currentTime =
          '${now.year}-${now.month.toString().padLeft(2, '0')}-${now.day.toString().padLeft(2, '0')} ${now.hour.toString().padLeft(2, '0')}:${now.minute.toString().padLeft(2, '0')}:${now.second.toString().padLeft(2, '0')}';
    });
  }

  @override
  Widget build(BuildContext context) {
    return Text(
      _currentTime ?? '',
      style: const TextStyle(color: Colors.white, fontSize: 10),
    );
  }
}
